<?php echo $this->element('displayHeader'); ?>
<?php echo $ajax->form('SSi', 'post', array('update' => 'content', 'indicator' => 'indicator', 'url' => array('action' => 'save'))); ?>
<div class="toolbar">
    <div id="tLeft">
        <?php if ($mode == 'add') : ?>
            <?php echo $this->element('toolbar', array('buttons' => array('save', 'clear', 'back'))); ?>
        <?php else :  // mode edit ?>
            <?php echo $this->element('toolbar', array('buttons' => array('add', array('print' => array('model' => 'SSiH')), 'back'))); ?>
        <?php endif; ?>
    </div>
    <div id="tRight"><?php echo $this->element('neighbors', array('model' => 'SSiH', 'title' => 'id')); ?></div>
</div>

<?php echo $form->input('SSiH.id'); ?>
<fieldset>
    <table>
        <tr>
            <td width="180px"><?php echo $form->label('SSiH.stock_in_no', 'Stock in no.'); ?></td>
            <td width="300px">
                <?php if ($mode == 'add') : ?>
                    -
                <?php else : ?>
                    <?php echo $this->data['SSiH']['stock_in_no'] ?>
                <?php endif; ?>
            </td>
            <td width="120px"><?php echo $form->label('SSiH.customer_id', 'Customer', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                    <?php echo $form->hidden('SSiH.customer_id', array('id' => 'hidSSiHCustomerId')); ?>
                    <?php echo $form->select('SSiH.customer_id', $customers); ?>
                <?php else : ?>
                    <?php echo $form->hidden('SSiH.customer_id'); ?>
                    <span id="customer_id"><?php echo $this->data['Customer']['name'] ?></span>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('SSiH.stock_in_date', 'Stock in date', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                    <?php echo $html->tag('span', $today); ?>
                    <?php echo $form->hidden('SSiH.stock_in_date', array('id' => 'stock_in_date', 'value' => $today)); ?>
                <?php else : ?>
                    <span id="stock_in_date"><?php echo $this->data['SSiH']['stock_in_date'] ?></span>
                <?php endif; ?>
            </td>
            <td><?php echo $form->label('SSiH.site_id', 'Site', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                    <?php echo $form->hidden('SSiH.site_id', array('id' => 'hidSSiHSiteId')); ?>
                    <?php echo $form->select('SSiH.site_id'); ?>
                <?php else : ?>
                    <?php echo $form->hidden('SSiH.site_id'); ?>
                    <span id="site_id"><?php echo $this->data['Site']['name']; ?></span>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('SSiH.stock_in_by', 'Stock in by'); ?></td>
            <td colspan="3">
                <?php if ($mode == 'add') : ?>
                    <?php echo $html->tag('span', $stock_in_by); ?>
                    <?php echo $form->hidden('SSiH.stock_in_by', array('value' => $stock_in_by)); ?>
                <?php else : ?>
                    <?php echo $html->tag('span', $this->data['SSiH']['stock_in_by']); ?>
                <?php endif; ?>
            </td>
        </tr>
    </table>
</fieldset>

<fieldset>
    <table class="data">
        <thead>
            <tr>
                <th class="no">No</th>
                <th width="200px">Part no.</th>
                <th width="180px">Stock Code</th>
                <th>Description</th>
                <th width="90px">Stock in Qty</th>
                <th width="50px">Unit</th>
                <th width="80px">Cost</th>
                <th width="80px">Amount</th>
                <?php if ($mode == 'add') : ?>
                    <th class="action">&nbsp;</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody id="productRow">
            <?php if ($mode == 'add') : ?>
            <?php else : $count = count($this->data['SSi'])// mode edit ?>
                <?php for ($i = 0; $i < $count; ++$i) : ?>
                    <tr class="<?php echo (($i + 1) % 2 == 0) ? 'even-cell' : 'odd-cell'; ?>">
                        <td><span><?php echo $i + 1; ?></span></td>
                        <td><?php echo $html->link($this->data['SSi'][$i]['Product']['supplier_part_no'], '/supplier_inventories/view/' . $this->data['SSi'][$i]['cust_product_site_id'], array('target' => '_blank')); ?></td>
                        <td><?php echo $this->data['SSi'][$i]['CustProductSite']['stock_code']; ?></td>
                        <td><?php echo $this->data['SSi'][$i]['Product']['title']; ?></td>
                        <td class="text-right"><?php echo $this->data['SSi'][$i]['stock_in_qty']; ?></td>
                        <td class="center"><?php echo $this->data['SSi'][$i]['Product']['Unit']['title']; ?></td>
                        <td class="text-right"><?php echo number_format($this->data['SSi'][$i]['cost'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($this->data['SSi'][$i]['cost'] * $this->data['SSi'][$i]['stock_in_qty'], 2); ?></td>
                    </tr>
                <?php endfor; ?>
            <?php endif; ?>
        </tbody>
    </table>
</fieldset>

<fieldset>
    <table>
        <tr>
            <td width="80px"><?php echo $form->label('SSiH.remark'); ?></td>
            <td><?php 
            if ($mode == 'add') { 
                echo $form->textarea('SSiH.remark', array('rows' => 3, 'cols' => 50)); 
            } else {
                echo $this->data['SSiH']['remark'];
            }
            ?></td>
        </tr>
    </table>
</fieldset>

<?php echo $form->end(); ?>

<?php if ($mode == 'add') : ?>
    <script type="text/javascript">
        var partNos = {};

        requestProduct = function(event) {
            var element = Event.element(event);
            var part_no = $j.trim($F(element)).toUpperCase();
            var no = element.readAttribute("no");   // ลำดั�?�?ถว�?ั�?�?ุ�?ั�? เริ�?มที�? 0

            if(part_no.length == 0) {
                return;
            } else if ($j("#SSiHCustomerId").val() == '') {
                alert("Please select a customer first");
                $(event.target).clear();
                return;
            } else if ($j("#SSiHSiteId").val() == '') {
                alert("Please select a customer site first");
                $(event.target).clear();
                return;
            } else {
                $j("#SSiHCustomerId").attr('disabled', true);
                $j("#hidSSiHCustomerId").val($j("#SSiHCustomerId").val());
                $j("#SSiHSiteId").attr('disabled', true);
                $j("#hidSSiHSiteId").val($j("#SSiHSiteId").val());
            }

            if (partNos[part_no] == null) {
                var url = base + "/supplier_customer_inventories/json_find_by_supplier_part_no_site_id/";
                var params = {supplier_part_no: part_no, site_id: $j("#SSiHSiteId").val()};
                postRequest(url, params, function(data) {
                    if (data.CustProductSite) { // �?�? Product
                    } else {
                        alert("No product found.");
                        element.clear();
                        $("SSi" + no + "PartNo").focus();
                        return;
                    }
                    setSSi(data, part_no, no);
                });
            } else {
                element.clear();
                var row = partNos[part_no]; // �?ถวที�?มี part_no �?ี�?อยู�?
                $j("#SSi" + row + "StockInQty").val(parseInt($j("#SSi" + row + "StockInQty").val()) + 1);
                calAmount(no);
                setTimeout(function() {
                    $("SSi" + no + "PartNo").focus();
                }, 100);
            }
        }

        setSSi = function(data, part_no, no) {
            $j("#SSi" + no + "Text").text(data.CustProductSite.text);
            $j("#SSi" + no + "PartNo").hide();
            $j("#linkSSi" + no + "ProductId").hide();
            $j("#spanSSi" + no + "PartNo").text(data.Product.supplier_part_no).show();
            $j("#SSi" + no + "StockCode").text(data.CustProductSite.stock_code);
            $j("#SSi" + no + "ProductId").val(data.Product.id);
            $j("#SSi" + no + "Cost").val(data.Product.cost);
            $j("#SSi" + no + "CustProductSiteId").val(data.CustProductSite.id);
            $j("#SSi" + no + "Unit").text(data.Product.Unit.title);
            $j("#SSi" + no + "StockInQty").val(1);

            // ดักจับ Event กดลบแถว
            $j('#linkSSi' + no + 'Delete').bind('click', function() {
                // ลบรายการ part no ออกจาก list
                var p = $j("#spanSSi" + no + "PartNo").text();
                partNos[p] = undefined;

                // ลบ แถว
                $j('#SSi' + no + 'Id').parents('tr').remove();

                // จัดลำดับตัวเลขหน้าแถวใหม่
                $j('#productRow').runno();
            }).show();

            calAmount(no);

            partNos[part_no] = no;  // �?ั�?ทึ�?�?ถว�?ั�?�?ุ�?ั�?�?อ�? part no
            var nextRow = (parseInt(no) + 1);
            createRow(nextRow)
            $("SSi" + nextRow + "PartNo").focus();
        }

        calAmount = function(no) {
            var qty = parseInt($j("#SSi" + no + "StockInQty").val());
            var price = parseFloat($j("#SSi" + no + "Cost").val()) | 0;
            var amount = qty * price;
            $j("#SSi" + no + "Amount").text(amount.toFixed(2));
        }

        createRow = function(row, data) {
            var tr = $j("<tr>").attr({no: row}).addClass(((row + 1) % 2 == 0)? "even-cell" : "odd-cell")
            .append($j("<td class='center'>&nbsp;</td>"))
            .append($j('<td><span id="spanSSi' + row + 'PartNo"></span></td>')
            .append('<input id="SSi' + row + 'Id" type="hidden" value="" name="data[SSi][' + row + '][id]" no="' + row + '" />')
            .append('<input id="SSi' + row + 'PartNo" type="text" value="" no="' + row + '" />')
            .append('<input id="SSi' + row + 'ProductId" type="hidden" value="" name="data[SSi][' + row + '][product_id]"/>')
            .append('<input id="SSi' + row + 'CustProductSiteId" type="hidden" value="" name="data[SSi][' + row + '][cust_product_site_id]"/>')
            .append('&nbsp;<a href="#" id="linkSSi' + row + 'ProductId"><?php echo $html->image('icon/search.png'); ?></a>'))
            .append($j('<td><span id="SSi' + row + 'StockCode"></span></td>'))
            .append($j('<td><span id="SSi' + row + 'Text"></span></td>'))
            .append($j('<td></td>').addClass('text-right')
            .append('<input id="SSi' + row + 'StockInQty" no="' + row + '" type="text" size="7" class="text-right" value="" name="data[SSi][' + row + '][stock_in_qty]"/>'))
            .append($j('<td><span id="SSi' + row + 'Unit"></span></td>').addClass('center'))
            .append($j('<td></td>').addClass('text-right')
            .append('<input id="SSi' + row + 'Cost" no="' + row + '" type="text" size="7" class="text-right" value="" name="data[SSi][' + row + '][cost]"/>'))
            .append($j('<td class="text-right"><span id="SSi' + row + 'Amount"></span></td>'))
            tr.append($j('<td><a href="#" id="linkSSi' + row + 'Delete" style="display: none;"><?php echo $html->image('icon/delete.png', array('title' => 'Delete', 'alt' => 'Delete')); ?></a></td>').addClass('center'));
            tr.appendTo("#productRow");
            $j('#productRow').runno();

            addRowListener(row);
        };

        addRowListener = function(row) {
            $j("#SSi" + row + "PartNo").bind('keypress', partNoKeyPress);
            $j("#SSi" + row + "PartNo").bind('blur', function(event) {
                requestProduct(event);
            });

            $j("#linkSSi" + row + "ProductId").bind('click', function(event) {
                if ($j("#SSiHSiteId").val() == "") {
                    alert("Please select a customer site.");
                    return;
                }

                var url = base + "/supplier_customer_inventories/popup_view";

                url += "/" + $j('#SSiHCustomerId').val();
                url += "/" + $j('#SSiHSiteId').val();

                requestPopup(url, "productsHandler");
            });

            $j("#SSi" + row + "StockInQty, #SSi" + row + "Cost").bind('keypress', stopKeyEnter);
            $j("#SSi" + row + "StockInQty, #SSi" + row + "Cost").bind('change', function(event) {
                calAmount($j(this).attr("no"));
            });
        };

        productsHandler = function(part_no) {
            if (part_no != null) {
                // หา input part no ที่ยังแสดงอยู่ (มีอันเดียวเสมอ)
                if ($j.browser.msie == true) {
                    $j("input[id$=PartNo]:visible").val(part_no).focus();
                } else {
                    $j("input[id$=PartNo]:visible").val(part_no).focus().blur();
                }
            }
        }

        /**
         * onload
         */
        $j(function() {
            /**
             * validate ข้อมูลด้วย javascript ก่อน Save
             */
            $j('#SSiHId').parent('form').beforeSubmit(function() {
                if ($j.areEmpty('SSiHCustomerId', 'SSiHSiteId')) {
                    return false;
                }

                if ($j('#SSi0PartNo').length == 0) {
                    if (!$j.validateField('SSi0PartNo', 'Product', 'SSi0PartNo')) {
                        return false;
                    }
                }

                if (!$j.validateColumns('StockInQty', 'Stock in Qty', {callback: $j.QTY})) {
                    return false;
                }

                if (!$j.validateColumns('Cost', 'Cost', {callback: $j.AMOUNT})) {
                    return false;
                }
                return true;
            });

            $j("#SSiHCustomerId").bind('change', function() {
                $j('#SSiHSiteId').requestOptions("sites/option_list", $j("#SSiHCustomerId").val());
            });
            createRow(0);
        });
    </script>
<?php endif; ?>